package com.jule.teenpatti.mail.network;

import com.jule.core.configuration.ThreadConfig;
import com.jule.core.network.codec.FrameDecoder;
import com.jule.core.network.codec.FramePrepender;
import com.jule.teenpatti.mail.config.Config;
import com.jule.teenpatti.mail.network.codec.RequestDecoder;
import com.jule.teenpatti.mail.network.codec.ResponseEncoder;
import com.jule.teenpatti.mail.network.handler.IoHandler;
import com.jule.teenpatti.mail.service.RegisterService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by lyb on 2018/6/19
 */
@Slf4j
public class IOServer {
    private static final ServerBootstrap bootstrap = new ServerBootstrap();

    public static void connect() {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(ThreadConfig.CHILD_GROUP_THREADS);
        try {
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_REUSEADDR, true)
                    .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15 * 1000)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast("Idl", new IdleStateHandler(10, 10, 10));
                            p.addLast("FramePrepender", new FramePrepender());
                            p.addLast("FrameDecoder", new FrameDecoder());
                            p.addLast("ResponseDecoder", new ResponseEncoder());
                            p.addLast("RequestEncoder", new RequestDecoder());
                            p.addLast("IoHandler", new IoHandler());
                        }
                    });

            bootstrap.bind(Config.BIND_IP,Config.BIND_PORT).addListener(
                    (ChannelFutureListener) future -> RegisterService.getInstance().onServiceStartUp());
            log.info("mail service bind port " + Config.BIND_PORT);
        } catch (Exception e) {
            log.error("", e);
        }
    }
}
